package com.yoo.module_base.utils

import android.app.Activity
import android.content.Context
import android.os.Build
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText

object SoftInputFromUtil {
    /**
     * EditText获取焦点并显示软键盘
     */
    fun showSoftInputFromWindow(editText: EditText) {
        editText.isFocusable = true
        editText.isFocusableInTouchMode = true
        editText.requestFocus()
        val inputManager =
            editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManager.showSoftInput(editText, 0)
    }

    fun forceHideSoftInput(activity: Activity) {
        val keyboard = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        //activity.currentFocus?.windowToken 是获取当前activity的windowToken
        keyboard.hideSoftInputFromWindow(activity.currentFocus?.windowToken, 0)
    }


    /**
     * 隐藏软键盘(只适用于Activity，不适用于Fragment)
     */
    fun hideSoftKeyboard(activity: Activity) {
        try {
            val currentFocus = activity.currentFocus
            //            View currentFocus = activity.getWindow().peekDecorView();
            if (currentFocus != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
                    val inputMethodManager =
                        activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
                    inputMethodManager.hideSoftInputFromWindow(
                        currentFocus.windowToken,
                        InputMethodManager.HIDE_NOT_ALWAYS
                    )
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun hideKeyboard(activity: Activity?, view: View?) {
        if (activity != null) {
            if (view != null) {
                val imm =
                    activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
                imm?.hideSoftInputFromWindow(view.getWindowToken(), 0)
            } else {
                hideKeyboard(activity)
            }
        }
    }

    private fun hideKeyboard(activity: Activity?) {
        if (activity != null) {
            val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
            if (activity.currentFocus != null) {
                imm?.hideSoftInputFromWindow(activity.currentFocus!!.windowToken, 0)
                if (null != activity.currentFocus) {
                    activity.currentFocus!!.clearFocus()
                }
            }
        }
    }
}